package com.cws.project.cws.graduation.project.controller;

import java.util.List;
import java.util.stream.Collectors;

import com.cws.common.utils.DateUtils;
import com.cws.common.utils.file.FileUtils;
import com.cws.common.utils.poi.ExcelUtil;
import com.cws.framework.aspectj.lang.annotation.Log;
import com.cws.framework.aspectj.lang.enums.BusinessType;
import com.cws.framework.web.controller.BaseController;
import com.cws.framework.web.domain.AjaxResult;
import com.cws.framework.web.page.TableDataInfo;
import com.cws.project.cws.clazz.domain.ClazzUser;
import com.cws.project.cws.clazz.service.IClazzService;
import com.cws.project.cws.clazz.service.IClazzUserService;
import com.cws.project.cws.score.controller.HomeworkScoreController;
import com.cws.project.cws.score.domain.HomeworkScore;
import com.cws.project.cws.teacher.domain.Teacher;
import com.cws.project.cws.teacher.service.ITeacherService;
import com.cws.project.system.user.domain.User;
import com.cws.project.system.user.service.IUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cws.project.cws.graduation.project.domain.GraduationProject;
import com.cws.project.cws.graduation.project.service.IGraduationProjectService;

import javax.servlet.http.HttpServletResponse;

/**
 * 毕设内容Controller
 *
 * @author xyl
 * @date 2022-01-19
 */
@Controller
@RequestMapping("/cws/graduation/project")
public class GraduationProjectController extends BaseController {
    private String prefix = "cws/graduation/project";

    private static final Logger log = LoggerFactory.getLogger(GraduationProjectController.class);

    @Autowired
    private IGraduationProjectService graduationProjectService;
    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private IClazzUserService clazzUserService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IClazzService clazzService;

    @RequiresPermissions("cws:graduation:project:view")
    @GetMapping()
    public String project() {
        return prefix + "/project";
    }

//    @RequiresPermissions("cws:graduation:project:student:view")
//    @GetMapping("/student")
//    public String projectStudent() {
//        return prefix + "/student/project";
//    }

    @RequiresPermissions("cws:graduation:project:student:submit")
    @GetMapping("/student/submit")
    public String projectStudentSubmit(ModelMap mmap) {
        User sysUser = getSysUser();
        GraduationProject gp =   graduationProjectService.selectGraduationProjectByStudentId(sysUser.getUserId());
        if(ObjectUtils.isNotEmpty(gp)){
            mmap.put("gp", gp);
            return prefix + "/student/detail";
        }
        List<Teacher> teachers;
        if(sysUser.isStudent()){
            ClazzUser clazzUser =  clazzUserService.selectClazzUserByStudentId(sysUser.getUserId());
            Teacher tt = new Teacher();
            tt.setClazzId(clazzUser.getClazzId());
            teachers = teacherService.selectTeacherList(tt);
        }else{
            teachers = teacherService.selectTeacherList(null);
        }
        mmap.put("teachers",teachers);
        return prefix + "/student/submit";
    }

    /**
     * 查询毕设内容列表
     */
    @RequiresPermissions("cws:graduation:project:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GraduationProject graduationProject) {
        startPage();
        User sysUser = getSysUser();
        if(sysUser.isTeacher()){
            graduationProject.setTeacherId(sysUser.getUserId());
        }else if(sysUser.isStudent()){
            graduationProject.setTeacherId(-1L);
        }else if(sysUser.isInstructor()){
            ClazzUser clazzUser = new ClazzUser();
            clazzUser.setUserId(sysUser.getUserId());
            graduationProject.setClazzIds(clazzUserService.selectClazzUserList(clazzUser).stream().map(ClazzUser::getClazzId).collect(Collectors.toList()));
        }
        List<GraduationProject> list = graduationProjectService.selectGraduationProjectList(graduationProject);
        return getDataTable(list);
    }

    /**
     * 导出毕设内容列表
     */
    @RequiresPermissions("cws:graduation:project:export")
    @Log(title = "毕设内容", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GraduationProject graduationProject) {
        User sysUser = getSysUser();
        if(!sysUser.isAdmin()){
            graduationProject.setTeacherId(sysUser.getUserId());
        }
        List<GraduationProject> list = graduationProjectService.selectGraduationProjectList(graduationProject);
        ExcelUtil<GraduationProject> util = new ExcelUtil<GraduationProject>(GraduationProject.class);
        return util.exportExcel(list, "project");
    }

    /**
     * 新增毕设内容
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存毕设内容
     */
    @RequiresPermissions("cws:graduation:project:add")
    @Log(title = "毕设内容", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(GraduationProject graduationProject) {
        GraduationProject gp = graduationProjectService.selectGraduationProjectByStudentId(getUserId());
        if(ObjectUtils.isNotEmpty(gp)){
            return AjaxResult.error("请勿重复提交！");
        }
        graduationProject.setStudentId(getUserId());
        graduationProject.setCreateTime(DateUtils.getNowDate());
        graduationProject.setCreateBy(getLoginName());
        return toAjax(graduationProjectService.insertGraduationProject(graduationProject));
    }

    /**
     * 修改毕设内容
     */
    @GetMapping("/edit/{graduationProductId}")
    public String edit(@PathVariable("graduationProductId") Long graduationProductId, ModelMap mmap) {
        GraduationProject graduationProject = graduationProjectService.selectGraduationProjectById(graduationProductId);
        mmap.put("graduationProject", graduationProject);
        return prefix + "/edit";
    }

    /**
     * 修改保存毕设内容
     */
    @RequiresPermissions("cws:graduation:project:edit")
    @Log(title = "毕设内容", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GraduationProject graduationProject) {
        return toAjax(graduationProjectService.updateGraduationProject(graduationProject));
    }

    /**
     * 修改保存毕设内容
     */
    @RequiresPermissions("cws:graduation:project:download")
    @GetMapping("/download/{graduationProductId}")
    public void download(@PathVariable("graduationProductId") Long graduationProductId, HttpServletResponse response) throws Exception {
        GraduationProject gp = graduationProjectService.selectGraduationProjectById(graduationProductId);

        if(ObjectUtils.isEmpty(gp)){
            throw new Exception("非法请求！");
        }
        User user = userService.selectUserById(gp.getStudentId());
        try {
            String filePath = gp.getUrl().replace("http://localhost:8080/profile/", "D:/cws/uploadPath/");
            String fix = filePath.substring(filePath.lastIndexOf("."));
            String realFileName = gp.getTopic() + "-" + user.getLoginName() + "-" + user.getUserName() + fix;
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 删除毕设内容
     */
    @RequiresPermissions("cws:graduation:project:remove")
    @Log(title = "毕设内容", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(graduationProjectService.deleteGraduationProjectByIds(ids));
    }
}
